<template>
  <view>
    <!-- 竖向排列 row  -->
    <view
      class="_goods-detail"
      @click="onDetail(detail)"
    >
      <view class="_goods-img">
        <view class="_tips" v-if="detail.wellChosen"></view>
        <view class="_tips-history" v-if="productHistoryList.indexOf(detail.productId) > -1 && nowTime < expire || isShowHistory">您的浏览足迹</view>
        <view class="_pic" :style="{'height': picHeight+'px'}">
          <x-image :src="formatOss(detail.productMainPic)" mode="widthFix"/>
        </view>
      </view>
      <view class="_goods-title">
        <view style="position: relative;width: 100%;display: flex;align-items: center;">
          <view class="_indent2">
            <view v-if="isTag.brand" class="tag tag-brand"></view>
            <view v-if="isTag.subsidy" class="tag tag-subsidy"></view>
            <view v-if="isTag.new" class="tag tag-new"></view>
            <view v-if="isTag.hot" class="tag tag-hot"></view>
            <text>{{ detail.productTitle }}</text>
          </view>
        </view>
        <view class="_goods-price">
          <text v-if="detail.couponType === 2" class="_text">券后</text>
          <view class="flex1">
            <x-price
              v-if="detail.couponType === 2"
              :price="detail.subsidyPrice ? (detail.subsidyPrice - detail.couponAmount > 0 ? detail.subsidyPrice - detail.couponAmount : '0.01' )
              : (detail.productPrice - detail.couponAmount > 0 ? detail.productPrice - detail.couponAmount : '0.01')"
              color="#DE3A2E"
              :TipsSize="26"
              :Price1Size="38"
              :Price2Size="26"
            />
            <x-price v-else-if="detail.subsidyPrice" :price="detail.subsidyPrice" color="#DE3A2E" :TipsSize="26" :Price1Size="38" :Price2Size="26"/>
            <x-price v-else :price="detail.productPrice" color="#DE3A2E" :TipsSize="26" :Price1Size="38" :Price2Size="26"/>
          </view>
          <text class="_sales">
            <text v-if="rate && rate > 90">{{ rate }}%好评率</text>
            <text v-else>总售{{ numberFormat(detail.salesNum) }}件</text>
          </text>
        </view>
        <view class="_discount" v-if="detail.couponType !== 0">
          <view class="_title">
            <text class="_tips" >
              <text v-if="detail.couponType === 1">满{{ detail.transactionAmount }}</text>
              <text v-else>立</text>
              减{{ detail.couponAmount }}元
            </text>
          </view>
        </view>
        <view class="_block1" v-if="(!(detail.levelSecondCategoryName && detail.productRanking <= 10) && detail.sourceFactory) || showSourceFactory" @click.stop="onSourceFactory">
          <text class="_text">源头工厂</text>
          <x-icon class="_icon" name="icon-017" size="18" color="#8958DF"/>
        </view>
        <view class="_indent1" v-if="detail.productSellingPoint">{{ detail.productSellingPoint || '' }}</view>
        <view class="_block2" v-if="detail.levelSecondCategoryName && detail.productRanking <= 10 && showRanking" @click.stop="onRanking(detail)">
          <x-icon name="icon-049" size="26" color="#ED6A0C"/>
          <text class="_text">{{ detail.levelSecondCategoryName + 'TOP' + detail.productRanking }}</text>
          <x-icon name="icon-017" size="18" color="#ED6A0C"/>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import $sr from '@/utils/x-sr';
import XIcon from '@/components/x-icon';
import XImage from '@/components/x-image';
import XPrice from '@/components/x-price';

export default {
  name: 'XGoodsItem',
  components: {
    XPrice,
    XIcon,
    XImage
  },
  props: {
    detail: {
      type: Object,
      default: () => {}
    },
    componentId: {
      type: [String, Number],
      default: ''
    },
    showRanking: {
      type: Boolean,
      default: true
    },
    showSourceFactory: {
      type: Boolean,
      default: false
    },
    sourcePageType: {
      type: [String, Object],
      default: ''
    },
    sourcePageId: {
      type: [String, Object],
      default: ''
    },
    source: {
      type: [String, Object],
      default: ''
    }
  },
  computed: {
    isNewProduct() {
      if (this.detail.createdTime) {
        // const time = new Date(this.detail.createdTime.replace(/\-/gi, '/')).getTime();
        // const nowTime = new Date().getTime();
        // return (nowTime - time) < (60 * 60 * 24 * 7 * 1000);

        const now = new Date();
        const creatTime = new Date(this.detail.createdTime.replace(/\-/gi, '/'));
        const firstdayoffset = (now.getDay() === 0 ? 7 : now.getDay()) - 1;
        now.setDate(now.getDate() - firstdayoffset - 1);
        let firstday = now.toISOString().substring(0, 10); // 获取本周第一天
        firstday = new Date(firstday);
        now.setDate(now.getDate() + 8);
        let lastday = now.toISOString().substring(0, 10); // 获取本周第最后一天
        lastday = new Date(lastday);
        if (creatTime > firstday && creatTime < lastday) {
          // 本周
          return true;
        } else {
          // 非本周
          return false;
        }
      } else {
        return false;
      }
    },
    isTag() {
      const params = {
        brand: false,
        subsidy: false,
        new: false,
        hot: false
      };
      let sort = 0;
      if (this.detail.productBrand) {
        params.brand = true;
        sort += 1;
      }
      if (this.detail.subsidyAmount > 0) {
        params.subsidy = true;
        sort += 1;
      }
      if (this.isNewProduct) {
        params.new = true;
        if (sort < 2) {
          sort += 1;
        } else {
          params.new = false;
        }
      }
      if (this.detail.salesNum > 2000) {
        params.hot = true;
        if (sort < 2) {
          sort += 1;
        } else {
          params.hot = false;
        }
      }
      return params;
    }
  },
  data() {
    return {
      picHeight: '',
      allHeight: '',
      productHistoryList: uni.getStorageSync('productHistory') || [],
      nowTime: new Date().getTime(),
      expire: uni.getStorageSync('expire') || 0,
      rate: '',
      isShowHistory: false,
      ratio: null,
      retryCount: 0
    };
  },
  created() {
    this.retryCount = 0;
    this.srTrack('expose_sku_component');
    const windowInfo = wx.getWindowInfo();
    this.ratio = (375 / windowInfo.windowWidth);
    this.picHeight = 171 * this.detail.mainPicHeight / this.detail.mainPicWidth / this.ratio;
  },
  mounted() {
    this.setHeight();
    if (this.nowTime > this.expire) {
      uni.removeStorageSync('productHistory');
      uni.removeStorageSync('expire');
    }
    // this.getRate();
  },
  methods: {
    numberFormat(val) {
      return this.$tools.numberFormat(val);
    },
    // 格式化图片
    formatOss(url) {
      return this.$tools.formatOss(url, 300);
    },
    // 源头工厂跳转
    onSourceFactory() {
      uni.navigateTo({
        url: '/packages/activity/source-factory/index'
      });
    },
    // 排行榜跳转
    onRanking(detail) {
      uni.navigateTo({
        url: `/packages/ranking/list/index?id=${detail.levelSecondCategoryId}`
      });
    },
    // 商品详情跳转
    onDetail(detail) {
      if (this.componentId) {
        this.$XTrack('onListToDetailEvent', {
          componentId: this.componentId,
          productId: detail.productId
        });
      }
      this.srTrack('trigger_sku_component');
      const query = this.$tools.object2param({
        productId: detail.productId,
        sourcePageType: this.sourcePageType,
        sourcePageId: this.sourcePageId,
        source: this.source
      });
      uni.navigateTo({
        url: `/pages/transit-product/index?${query}`,
        success: () => {
          setTimeout(() => {
            this.isShowHistory = true;
          }, 1000);
        }
      });
    },
    // 获取好评率
    async getRate() {
      const params = {
        productIdList: [this.detail.productId]
      };
      this.$http({
        login: true,
        url: '/product/comment/praise/rate/list',
        data: params,
        method: 'post',
        report: false
      }).then(res => {
        if (res.data && res.data.length > 0) {
          this.rate = res.data[0].praiseRate;
        }
      }).catch(() => {
      });
    },
    setHeight() {
      this.$nextTick(() => {
        const query = uni.createSelectorQuery().in(this);
        query.select('._goods-detail').boundingClientRect(data => {
          if (data?.height) {
            this.allHeight = data.height;
            this.$emit('mounted', data.height + 8 / this.ratio, this.detail);
          } else {
            // 获取不到时，重试三次
            if (this.retryCount < 3) {
              setTimeout(() => {
                this.retryCount++;
                this.setHeight();
              }, 600);
            }
          }
        }).exec();
      });
    },
    // 有数上报
    srTrack(name) {
      $sr.trackProductCard(name, this.detail);
    }
  }
};
</script>

<style lang="scss">
._goods-detail {
  box-sizing: border-box;
  width: 343px;
  border-radius: 10px;
  overflow: hidden;
  margin-bottom: 16px;

  ._goods-img {
    flex-shrink: 0;
    position: relative;
    width: 343px;
    //height: 343px;
    background: #FFE4E4;
    .pic{
      width: 100%;
    }

    ._tips {
      position: absolute;
      top: 0;
      left: 0;
      width: 120px;
      height: 44px;
      background: cdn('/images/99selected.png', true) no-repeat 0 0;
      background-size: contain;
      border-radius: 10px 0 0 0;
    }
    ._tips-history{
      position: absolute;
      bottom: 20px;
      left: 50%;
      transform: translateX(-50%);
      min-width: 200px;
      height: 42px;
      line-height: 42px;
      font-size: 28px;
      text-align: center;
      color: #fff;
      background: rgba(222, 58, 46, 0.8);
      border-radius: 6px;
    }
  }

  ._goods-title {
    background: #fff;
    padding: 14px 20px;

    ._indent2 {
      flex: 1;
      font-size: 30px;
      line-height: 1.6;
      -webkit-line-clamp: 2;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      color: $uni-color-default;
      overflow: hidden;
      text-overflow: ellipsis;
      word-break: break-all;
      .tag{ position: relative; top: 6px; display:inline-block;width: 54px;height: 32px; border-radius: 4px;overflow: hidden; margin-right: 10px; background-position: center; background-repeat: no-repeat; background-size: contain;}
      .tag-new{ background-image: cdn('/images/goods-new.png');}
      .tag-brand{ background-image: cdn('/images/goods-brand.png');}
      .tag-hot{ background-image: cdn('/images/goods-hot.png');}
      .tag-subsidy{width: 104px; background-image: cdn('/images/goods-subsidy.png');}
    }

    ._indent1 {
      margin-top: 6px;
      border-radius: 6px;
      color: #A6734E;
      font-size: 24px;
      font-weight: normal;
      -webkit-line-clamp: 1;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
      word-break: break-all;
    }
    ._block1{
      //width: 150px;
      display: inline-flex;
      align-items: center;
      background: #F1E9FF;
      border-radius: 6px;
      margin-top: 12px;
      padding: 2px 10px;
      color: #8958DF;
      font-size: 26px;
      ._text{
        margin-right: 10px;
      }
    }
    ._block2{
      border-top: 2px solid #F6F6F6;
      display: flex;
      align-items: center;
      border-radius: 6px;
      margin-top: 12px;
      padding-top: 12px;
      color: #ED6A0C;
      font-size: 26px;
      font-weight: bold;
      ._text{
        margin: 0 6px;
        flex: 1;
      }
    }

    ._discount{
      margin-top: 2px;
      display: flex; align-items: center; font-size: $uni-font-size-sm;
      ._title{
        flex: 1; text-align: left; align-items: center; height: 40px; overflow: hidden;
        ._tips{
          display: inline-block;
          color: $uni-color-primary;
          background: #FFEAE9;
          text-align: center;
          padding: 0 8px;
          line-height: 32px;
          border-radius: 4px;
          margin-right: 8px;
          font-size: 24px;
          border: 2px solid $uni-color-primary;
        }
      }
    }

    ._goods-price {
      margin-top: 12px;
      display: flex;
      align-items: baseline;
      ._text{
        color: #DE3A2E;
        font-size: 22px;
        margin-right: 4px;
      }
      ._sales {
        color: #8E8E8E;
        font-size: 24px;
        line-height: 24px;
        padding: 0 4px;
        display: flex;
        align-items: center;
        ._line{
          display: inline-block;
          width: 2px;
          height: 24px;
          background: #8E8E8E;
          margin: 0 8px;
        }
      }
    }
  }
}

</style>
